package com.example.shushiyunsst.fragment.main.wallet.sub

import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.widget.Toolbar
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.fastjson.JSON
import com.example.library_common.adapter.JssBaseQuickAdapter
import com.example.library_common.adapter.JssBaseViewHolder
import com.example.library_common.base.BaseFragmentEx
import com.example.library_common.base.SimpleListFragment
import com.example.library_common.bean.CommonBean
import com.example.library_common.networking.RestClient
import com.example.library_common.utils.QMUIDeviceHelper
import com.example.library_common.utils.QMUIDisplayHelper
import com.example.shushiyunsst.R
import com.example.shushiyunsst.fragment.main.wallet.bean.MyCaptureBean
import com.example.shushiyunsst.fragment.main.wallet.bean.WelfareBean
import com.example.wallet.db.UserInfoManager
import ikidou.reflect.TypeBuilder
import java.lang.reflect.Type
import kotlin.math.abs

/**
 *  查询积分释放详情
 * */
class WelfareFragment : SimpleListFragment<WelfareBean>() {

    companion object {
        fun newInstance(): WelfareFragment {
            val args = Bundle()
            val fragment = WelfareFragment()
            fragment.arguments = args
            return fragment
        }
    }

    private var mLabAdapter: JssBaseQuickAdapter<String>? = null

    //释放记录
    private val released = 1

    //获得记录
    private val required = 2

    private var queryType = released

    private val mLabMap = mapOf(
        released to "释放记录",
        required to "获得记录"
    )

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
//        isEnableLoadMore = false
        isAddDividerItemDecoration = false
    }

    override fun initView(view: View) {
        super.initView(view)
        view.setBackgroundResource(R.color.bg_color)
        mHeader.removeAllViews()
        addHeader(R.layout.comment_header_layout)
        val top: View = mHeader.findViewById(R.id.top)
        top.setBackgroundResource(R.color.bg_color_0)
        val mToolbar: Toolbar = view.findViewById(R.id.mToolbar)
        mToolbar.title = "积分释放详情"
        mToolbar.setNavigationOnClickListener { onBackPressedSupport() }

        addHeader(R.layout.welfare_header_fragment)

        val mLabRecyclerView: RecyclerView = mHeader.findViewById(R.id.mLabRecyclerView)
        mLabRecyclerView.setHasFixedSize(true)
        mLabRecyclerView.layoutManager = LinearLayoutManager(
            _mActivity, LinearLayoutManager.HORIZONTAL, false
        )
        mLabAdapter = object : JssBaseQuickAdapter<String>(R.layout.welfare_header_item_fragment) {

            override fun onCreateDefViewHolder(
                parent: ViewGroup,
                viewType: Int
            ): JssBaseViewHolder {
                val mHolder = super.onCreateDefViewHolder(parent, viewType)
                val layoutParams = mHolder.itemView.layoutParams
                val mGap = _mActivity.resources.getDimension(R.dimen.welfare_header_item_hor)
                val allGap = mGap * mLabMap.size
                layoutParams.width =
                    ((QMUIDisplayHelper.getScreenWidth(_mActivity) / mLabMap.size) - allGap).toInt()

                return mHolder
            }

            override fun convert(holder: JssBaseViewHolder?, item: String?) {
                super.convert(holder, item)
                holder?.setText(R.id.mRTextView, item)
                    ?.setViewSelect(R.id.mRTextView, item == mLabMap[queryType])
            }
        }
        mLabRecyclerView.adapter = mLabAdapter

        for (e in mLabMap) {
            mLabAdapter?.addData(e.value)
        }

        mLabAdapter?.setOnItemClickListener { _, _, position ->
            val current = mLabMap[queryType]

            val item = mLabAdapter?.getItem(position)

            if (current == item) {
                return@setOnItemClickListener
            }

            for (e in mLabMap) {
                if (e.value == item) {
                    queryType = e.key
                    mLabAdapter?.notifyDataSetChanged()
                    mLabRecyclerView.scrollToPosition(position)
                    break
                }
            }
            if (!mSwipeRefreshLayout.isRefreshing) {
                mSwipeRefreshLayout.isRefreshing = true
            }
            onRefresh()
        }
    }


    override fun getItemLayout(): Int {
        return R.layout.welfare_fragment
    }

    override fun convertItem(helper: JssBaseViewHolder?, item: WelfareBean?) {

        val titleStr = when (queryType) {
            released -> item?.typeContent
            required -> item?.typeContent
            else -> item?.typeContent
        }

        val destroyBalance = item?.destroyBalance ?: 0.0

        val publicWelfareBalance = item?.publicWelfareBalance ?: 0.0

        val extractFeeBalance = item?.extractFeeBalance ?: 0.0

        val numTvStr = item?.nums ?: 0.0

        val all =
            abs(extractFeeBalance) + abs(publicWelfareBalance) + abs(destroyBalance) + abs(numTvStr)

        helper?.setText(R.id.title, titleStr)
            ?.setText(R.id.numTv, item?.nums.toString())
            ?.setText(R.id.timeTv, item?.createTime)
            ?.setText(R.id.tvi, destroyBalance.toString())
            ?.setText(R.id.tvi_0, publicWelfareBalance.toString())
            ?.setText(R.id.tvi_1, extractFeeBalance.toString())
            ?.setText(R.id.allRelease, all.toString())
    }

    override fun getListType(): Type {
        return TypeBuilder.newInstance(CommonBean::class.java)
            .beginSubType(List::class.java)
            .addTypeParam(WelfareBean::class.java)
            .endSubType()
            .build()
    }

    override fun netRequest() {
        val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo
        RestClient.builder()
            .url(R.string.queryIntegralDetails)
            .raw(
                JSON.toJSONString(
                    mapOf(
                        "uid" to "${userInfo?.uid}",
                        "pageCount" to 10,
                        "pageIndex" to pageIndex,
                        "type" to queryType
                    )
                )
            )
            .success { parseDate(it) }
            .error { _, _ -> onFailed() }
            .failure { onFailed() }
            .build().post()
    }

    override fun parseDate(data: String?) {
//        super.parseDate(data)
        val obj = JSON.parseObject(data)
        val lsStr = obj["list"].toString()
        val list: List<WelfareBean> = JSON.parseArray(lsStr, WelfareBean::class.java)
        loadListDate(list)
    }
}